<template>
  <view>
    <uni-popup ref="tae" type="bottom" zindex>
      <view class="tea-box padding" @click.stop="closeall">
        <view class="top-title">
          <view class="modalTitle pad_cl">可选服务</view>
          <view class="pad_b48 padding-bottom-xs margin-top-sm text-c9 text-sm">请选择您想提前准备好的服务</view>
          <view class="close-btn" @click="close"><text class="cuIcon-close text-lg closBtn"></text></view>
        </view>

        <view scroll-y="true" class="smain_scroll">
          <!-- 茶水 -->
          <view class="smainCont">
            <view class="asitem">
              <view class="crise">茶水</view>
              <view class="crisList flex flex-wrap pad_cl minH102">
                <view class="ncheck_box numItem frew" v-for="(item, index) in drinkList"
                  @click.stop="tapDrink(item,index)" :key="index" :class="{ act: item.mnum > 0, invalid: !item.ext.saleTimesShow,selected: item.mnum > 0 }">
                  <text class="ncurrent text-cut flex align-center justify-center"
                    >
                    {{ item.name }}
                    <text class="cu-tag badge" v-if="item.mnum">{{item.mnum}}</text>
                  </text>
                  <scroll-view class="check_list" scroll-y="true" scroll-with-animation :class="{ show: item.show }">
                    <view v-for="(ditem, dindex) in item.mealNumber" :key="dindex"
                      @click.stop="chooseDrinkNum(dindex, ditem,item,index)" class="clitem"
                      :class="{ actc: ditem.sele }">
                      {{ ditem.num }}杯
                    </view>
                  </scroll-view>
                </view>
              </view>
            </view>
          </view>
          <!-- 用餐 -->
          <view class="smainCont">
            <view class="asitem">
              <view class="crise">用餐</view>
              <view class="crisList flex flex-wrap pad_cl minH102">
                <view class="ncheck_box numItem frew" v-for="(item, index) in mealList" 
                  @click.stop="tapMeal(item,index)" :key="index" >
                  <text class="ncurrent text-cut flex align-center justify-center" :class="{ act: item.mnum > 0, invalid: !item.ext.saleTimesShow }">
                    {{ item.name }}
                    <text class="cu-tag badge" v-if="item.mnum">{{item.mnum}}</text>
                  </text>
                  <scroll-view class="check_list" scroll-y="true" scroll-with-animation :class="{ show: item.show }">
                    <view v-for="(ditem, dindex) in mealNumber" :key="dindex"
                      @click.stop="chooseDrinkNum(dindex, ditem,item,index)" class="clitem"
                      :class="{ actc: drinkNumId == dindex }">
                      {{ ditem }}份
                    </view>
                  </scroll-view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <!-- 底部按钮 -->
        <view class="bottomBtn">
          <view class="submitBtnBox flex align-center">
            <view class="none flex sublef_new flex-six justify-center">
              <view class="text-center subcont" @click.stop="subPopBtnDel2">清空重选</view>
            </view>
            <view class="subBtn flex-sub" @click.stop="subPopBtn2">确定</view>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup lang="ts">
  import { ref, computed, onMounted } from 'vue'
  const emit = defineEmits(["confirm"])
  const tae = ref(null)
  const switchFlag = ref(false)
  const drinkId = ref(0)
  const drinkNumId = ref(-1)
  const mealNumber = ref([1, 2, 3, 4, 5, 6])
  const drinkNumber = ref([1, 2, 3, 4, 5, 6])
  const drinkList = ref([
    {
      create_time: "20230511105423",
      creator: 345,
      data_status: "20",
      default_time_nums: null,
      end_wt_time: null,
      ext: { saleTimesShow: true, saleTimes: [] },
      saleTimes: [],
      saleTimesShow: true,
      goods_id: 506,
      goods_spec_id: null,
      goods_spec_name: null,
      goods_type: "810",
      gtin_sku: "CS10018",
      labelNames: "茶",
      labels: "8",
      mstatus: null,
      name: "古丈毛尖",
      nparent_goods_id: null,
      nums: null,
      pushCache: true,
      seller_member_id: 16775,
      serviceGoodsName: null,
      start_wt_time: null,
      status: "233",
      time_slice_space: null,
      type: null,
      update_time: null,
      updator: null,
      weight: null,
      work_time_type: null,
      show: false,
      mnum: 0,
      mealNumber:[
       {
         num : 1,
         sele:false
       },
       {
         num : 2,
         sele:false
       },
       {
         num : 3,
         sele:false
       },
       {
         num : 4,
         sele:false
       },
       {
         num : 5,
         sele:false
       }
      ],
    },
    {
      create_time: "20230511105423",
      creator: 345,
      data_status: "20",
      default_time_nums: null,
      end_wt_time: null,
      ext: { saleTimesShow: true, saleTimes: [] },
      saleTimes: [],
      saleTimesShow: true,
      goods_id: 509,
      goods_spec_id: null,
      goods_spec_name: null,
      goods_type: "810",
      gtin_sku: "CS10016",
      labelNames: "茶",
      labels: "8",
      mstatus: null,
      name: "甘草莲心",
      nparent_goods_id: null,
      nums: null,
      pushCache: true,
      seller_member_id: 16775,
      serviceGoodsName: null,
      start_wt_time: null,
      status: "233",
      time_slice_space: null,
      type: null,
      update_time: null,
      updator: null,
      weight: null,
      work_time_type: null,
      show: false,
      mnum: 0,
      mealNumber:[
       {
         num : 1,
         sele:false
       },
       {
         num : 2,
         sele:false
       },
       {
         num : 3,
         sele:false
       },
       {
         num : 4,
         sele:false
       },
       {
         num : 5,
         sele:false
       }
      ],
    }
  ])
  const tuiList = ref([
    {
      id: '0',
      name: '店长推荐',
      price: '299'
    },
    {
      id: '1',
      name: '大家首选',
      price: '360'
    },
    {
      id: '2',
      name: '形象好',
      price: '380'
    }
  ])
  const mealList = ref([
    {
      create_time: "20230411161221",
      creator: 345,
      data_status: "20",
      default_time_nums: null,
      end_wt_time: null,
      mnum: 0,
      show: false,
      ext: {
        saleTimeStr: "煲仔饭提供时间(12:00-13:00,17:30-18:30)",
        saleTimes: [
          {
            create_time: "20230508111145",
            creator: null,
            data_status: "20",
            end_time: "1300",
            ext: {},
            goods_id: 343,
            goods_sale_time_id: 102,
            goods_spec_id: null,
            pushCache: true,
            start_time: "1200",
            update_time: null,
            updator: null
          },
          {
            create_time: "20230508111145",
            creator: null,
            data_status: "20",
            end_time: "1830",
            ext: {},
            goods_id: 343,
            goods_sale_time_id: 103,
            goods_spec_id: null,
            pushCache: true,
            start_time: "1730",
            update_time: null,
            updator: null
          }
        ],
        saleTimesShow: false
      },
      goods_id: 343,
      goods_spec_id: null,
      goods_spec_name: null,
      goods_type: "810",
      gtin_sku: "BZF001",
      labelNames: "餐",
      labels: "9",
      mstatus: null,
      name: "煲仔饭",
      nparent_goods_id: null,
      nums: null,
      pushCache: true,
      seller_member_id: 16775,
      serviceGoodsName: null,
      start_wt_time: null,
      status: "233",
      time_slice_space: null,
      type: null,
      update_time: null,
      updator: null,
      weight: null,
      work_time_type: null
    }
  ])
  const open = () => {
    tae.value.open()
  }

  const close = () => {
    tae.value.close()
  }

  // const tapSure = () => {
  //   emit("confirm", { statue: switchFlag.value })
  //   close()
  // }
  // drinkList.value.forEach(item => {
  //   item.mealNumber.forEach(citem=>{
  //     if(citem.sele){
  //       console.log('选中')
  //       const refundDetail = {
  //         name: item.name,          
  //         seleNum: citem.num   // 退货数量
  //       };
  //       skus.push(refundDetail);
  //     }
  //   })
  // })
  const changeSwitch = (e) => {
    switchFlag.value = e.detail
    console.log(e.detail, '---------------------', switchFlag.value)
  }
  const chooseDrinkNum = (index, ditem, item,findex) => {
    // let listId = drinkId.value
    item.mnum = ditem.num
    drinkList.value[findex].mealNumber.forEach(item=>{
      item.sele = false
    })
     console.log( )
    ditem.sele = true
    // let nnum = num;
    if (drinkNumId.value === index) {
      item.mnum = 0
      item.show = false
      drinkNumId.value = -1
      ditem.sele = false
      return
    }
    drinkNumId.value === index ? (drinkNumId.value = 0) : (drinkNumId.value = index);

    console.log(index, ditem, item)
    setTimeout(() => {
      item.show = false
    }, 100)
    // this.$set(this.drinkList[listId], 'mnum', nnum);
    // this.$set(this.drinkList[listId], 'showList', false);
  }

  // const initDMview = (type = 'all') => {
  //   console.log(type);
  //   if (type == 'drink' || type == 'all') {
  //     for (let i = 0; i < drinkList.value.length; i++) {
  //       if (drinkList[i].value.showList) {
  //         // this.$set(this.drinkList[i], 'showList', false);
  //         break;
  //       }
  //     }
  //   }
  //   if (type == 'meal' || type == 'all') {
  //     for (let i = 0; i < mealList.value.length; i++) {

  //     }
  //   }
  // }

  const toggleItemVisibility = (list, item) => {
    // 判断当前项是否已经显示
    if (item.show) {
      // 如果已显示，则关闭当前项
      item.show = false;
    } else {
      // 如果未显示，则先关闭所有项
      list.forEach((i) => {
        i.show = false;
      });
      // 然后打开当前项
      item.show = true;
    }
  };

  // tapDrink函数，调用通用函数
  const tapDrink = (item, index) => {
    toggleItemVisibility(drinkList.value, item);
  };

  // tapMeal函数，调用通用函数
  const tapMeal = (item, index) => {
    // 仅在 saleTimesShow 为 true 时才执行
    if (!item.ext.saleTimesShow) return;
    toggleItemVisibility(mealList.value, item);
  };

  const closeall = () => {
    drinkList.value.forEach((drink) => {
      drink.show = false;
    });
  }



  const chooseMealNum = (index, num) => {

  }
  //清空重新选
  const subPopBtnDel2 = () => {
    console.log('清空')
  }
  //确定
  const subPopBtn2 = () => {
    // const result = drinkList.value.map(item => {
    //     // 筛选出 sele 为 true 的 mealNumber 项
    //     const selectedItems = item.mealNumber.filter(meal => meal.sele === true);
    //     // if (selectedItems.length > 0) {
    //     //   return selectedItems.map(meal => ({
    //     //     name: item.name,
    //     //     num: meal.num
    //     //   }));
    //     // }
    //     if (selectedItems.length > 0) {
    //       // return selectedItems.map(meal => `${item.name}(${meal.num})`); // 格式化为 "name(num)"
    //       return selectedItems.reduce((sum, meal) => sum + meal.num, 0);
    //     }
    //     return null;
    //   }).filter(item => item !== null) // 过滤掉没有 sele 为 true 的项
    //   .flat(); // 将嵌套的数组展开
    
   const result = drinkList.value
     .map(item => {
       const selectedItems = item.mealNumber.filter(meal => meal.sele === true);
       return selectedItems.reduce((sum, meal) => sum + meal.num, 0);
     })
     .reduce((total, num) => total + num, 0); 
    emit("confirm", { statue: result })
    close()
  }
  
  const selectCountData = computed(() => {
    let result = [];
  
    // 遍历 drinkList.value
    drinkList.value.forEach(item => {
      // 遍历 item 的 mealNumber 数组
      item.mealNumber.forEach(citem => {
        // 判断 sele 是否为 true
        if (citem.sele) {
          // 将符合条件的项添加到 result 数组
          result.push({
            name: item.name,  // 提取 drinkList.item 的 name
            num: citem.num   // 提取 mealNumber.citem 的 num
          });
        }
      });
    });
  
    // 返回符合条件的所有项
    return result;
  });
  
  defineExpose({ open, close })
</script>

<style scoped lang="scss">
  .tea-box {
    background-color: #fff;
    border-radius: 16rpx 16rpx 0 0;
    padding-bottom: 40rpx;
    flex-shrink: 0;
    min-height: 702rpx;
    max-height: 96vh;
    position: relative;

    .smain_scroll {
      min-height: 384rpx;
      max-height: 50vh;
    }

    .crise {
      padding: 30rpx 48rpx 20rpx 0rpx;
      font-size: 28rpx;
      color: #666;
    }

    .invalid {
      color: #999;
      background: rgba(218, 218, 218, 0.5);
    }

    .act {
      color: #56bf7a !important;
      border: 1px solid #56bf7a;
      background: rgba(86, 191, 122, 0.15);
      border-radius: 8rpx;
    }

    .numItem.frew {
      width: 188rpx;
      height: 60rpx;
      max-width: 100%;
      margin: 0rpx 30rpx 0 0;
      border-radius: 8rpx;
      border: 1px solid #F2F5FC;
      color: #999;
    }

    .check_list {
      height: 240rpx;
      overflow-y: scroll;
      width: 188rpx;
      top: 69rpx;
      -webkit-transform-origin: top left !important;
      transform-origin: top left !important;
      position: absolute;
      background-color: #fff;
      left: 0;
      z-index: 2;
      text-align: center;
      color: #333;
      border-radius: 8rpx;
      transition: all 0.2s ease-out;
      opacity: 0;
      -webkit-transform: scale(0);
      transform: scale(0);
      -webkit-transform-origin: top left;
      transform-origin: top left;
      box-shadow: 0px 2px 18rpx rgba(0, 0, 0, 0.2);
    }

    .check_list.show {
      opacity: 1;
      -webkit-transform: scale(1);
      transform: scale(1);
    }

    .check_list .clitem {
      width: 100%;
      height: 80rpx;
      line-height: 81rpx;
    }

    .check_list .clitem.actc {
      color: #56bf7a;
    }

    .numItem {
      position: relative;
    }

    .ncurrent {
      width: 100%;
      height: 60rpx;
    }

    .modalTitle {
      font-size: 36rpx;
      font-weight: bold;
    }

    .close-btn {
      position: absolute;
      right: 30rpx;
      top: 30rpx;
    }
  }

  // 茶餐/备注-主-e
  // pop2-s弹窗
  .bottomBtn {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100vw;
    z-index: 98;

    .cenBox {
      position: relative;

      .cu-tag.badge {
        left: 0;
        right: auto;
      }
    }

    .submitBtnBox {
      margin: 0 0 40rpx 48rpx;
    }
  }

  .bottomBtn {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100vw;
    z-index: 98;
    .flex-six {
        flex: 0.6;
    }
    .cenBox {
      position: relative;

      .cu-tag.badge {
        left: 0;
        right: auto;
      }
    }

    .submitBtnBox {
      margin: 0 0 40rpx 48rpx;
    }
    .sublef_new {
        background-color: #404040;
        height: 100rpx;
        border-radius: 50rpx 0 0 50rpx;
    }
  }
  .submitBtnBox {
  	width: calc(100vw - 96rpx);
  	height: 100rpx;
  	color: #fff;
  	line-height: 99rpx;
  	.sublef {
  		background-color: #404040;
  		padding: 0 20rpx 0 0;
  		height: 100rpx;
  		border-radius: 50rpx 0 0 50rpx;
  		&.none {
  			.sback_btn {
  				width: 200rpx;
  				&::before {
  					content: none;
  				}
  				&::after {
  					content: none;
  				}
  			}
  		}
  		.subdis {
  			font-size: 20rpx;
  			margin-left: 10rpx;
  		}
  	}
  	.subPrice {
  		display: inline-block;
  		font-size: 40rpx;
  		font-weight: bold;
  		height: 100rpx;
  	}
  	.subBtn {
  		border-radius: 0 50rpx 50rpx 0;
  		text-align: center;
  		width: 192rpx;
  		height: 100rpx;
  		background-color: #56bf7a;
  		font-size: 28rpx;
  		&.gry {
  			background: #d0cfcf;
  		}
  		&.ban {
  			opacity: 0.88;
  		}
  	}
  }
  .numItem::before {
      content: '';
      position: absolute;
      right: 5rpx;
      bottom: 5rpx;
      width: 0;
      height: 0;
      border-bottom: 12rpx solid #e1e1e1;
      border-left: 12rpx solid transparent;
      border-bottom-width: 6px;
      border-bottom-style: solid;
      border-bottom-color: rgb(225, 225, 225);
      border-left-width: 6px;
      border-left-style: solid;
      border-left-color: transparent;
  }
  /* 选中状态下改变伪类的颜色 */
  .numItem.selected::before {
    border-bottom-color: #56bf7a !important; /* 选中时的颜色 */
  }
</style>